package myBinarySearch;

public class MyBinarySearch {

    public static int binarySearch(int[] srcArray, int des) {
        int left = 0;
        int right = srcArray.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (srcArray[mid] == des) {
                return mid;
            }
            if (des < srcArray[mid]) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

    // 测试二分查找方法
    public static void main(String[] args) {
        int[] srcArray = {1, 3, 5, 7, 9, 11, 13, 15};
        int des = 9;

        int index = binarySearch(srcArray, des);
        if (index != -1) {
            System.out.println("元素 " + des + " 在数组中的索引为: " + index);
        } else {
            System.out.println("数组中没有找到元素 " + des);
        }
    }
}
